﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Net.Http;
using System.ServiceModel;
using Microsoft.ApplicationServer.Http.Description;

namespace easytodoservice.Infrastructure
{
    public class ResourceFactory :IResourceFactory
    {
        private readonly CompositionContainer _container;

        public ResourceFactory(CompositionContainer container)
        {
            _container = container;
        }

        #region Implementation of IResourceFactory

        public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)
        {
            var contract = AttributedModelServices.GetContractName(serviceType);
            var identity = AttributedModelServices.GetTypeIdentity(serviceType);

            // force non-shared so that every service doesn't need to have a [PartCreationPolicy] attribute.
            var definition = new ContractBasedImportDefinition(contract, identity, null, ImportCardinality.ExactlyOne, false, false, CreationPolicy.NonShared);
            return _container.GetExports(definition).First().Value;
        }

        public void ReleaseInstance(InstanceContext instanceContext, object service)
        {
           
        }

        #endregion
    }
}